import Fruit from "./Fruit";
import Util from "./Util";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Player extends cc.Component {

    @property(cc.Node)
    parentPanel: cc.Node = null;

    public static instance: Player;

    //水果预制体
    @property([cc.Prefab])
    fruitPrefab: cc.Prefab[] = [];

    //画布，检测监听事件的载体
    @property(cc.Node)
    canvas: cc.Node = null;

    //当前操控对象
    controledfood: cc.Node = null;

    //分值文本
    @property(cc.Label)
    scoreLable: cc.Label = null;
    //分值文本
    @property(cc.Label)
    watermellonNumLable: cc.Label = null;
    //得分
    public score: number = 0;
    //得分
    public watermellonNum: number = 0;
    //危险提示
    @property(cc.Node)
    dangerous: cc.Node = null;
    //暂停
    @property(cc.Node)
    pause: cc.Node = null;
    //光
    @property(cc.Node)
    light: cc.Node = null;
    //危险
    public action: cc.ActionInterval = null;

    //击败多少玩家
    @property(cc.Node)
    beatNum: cc.Node = null;
    //得分结算
    @property(cc.Node)
    scoreNum: cc.Node = null;

    //游戏界面
    @property(cc.Node)
    gamePanel: cc.Node = null;
    //结算界面
    @property(cc.Node)
    endPanel: cc.Node = null;

    //危险界面
    @property(cc.Node)
    dangerPanel: cc.Node = null;

    fruitList: Fruit[] = [];

    dangerLine: number = 0;
    dieLine: number = 0;

    bannerAd;
    //背景光旋转
    public LightRotate() {
        var seq = cc.repeatForever(cc.rotateBy(20, 360));
        this.light.runAction(seq);
    }
    public isCanshowDangerous: boolean = true;
    //危险提示
    public Dangerous() {
        var _this = this;
        this.dangerous.runAction(this.action);
        this.isCanshowDangerous = false;
    }
    //结束
    public GameOver() {
        if(this.bannerAd){
            this.bannerAd.hide();
        }

        // 定义插屏广告
        let interstitialAd = null

        // 创建插屏广告实例，提前初始化
        if (wx.createInterstitialAd) {
            interstitialAd = wx.createInterstitialAd({
                adUnitId: 'adunit-268d35b602727564'
            })
        }

        // 在适合的场景显示插屏广告
        if (interstitialAd) {
            interstitialAd.show().catch((err) => {
                console.error(err)
            })
        }

        this.controledfood = null;
        // this.dangerous.stopAction(this.action);
        this.canvas.off(cc.Node.EventType.TOUCH_MOVE, this.MouseMove, this);
        this.canvas.off(cc.Node.EventType.TOUCH_END, this.MouseUp, this);
        this.canvas.off(cc.Node.EventType.TOUCH_CANCEL, this.MouseUp, this);
        this.canvas.off(cc.Node.EventType.TOUCH_START, this.MouseJump, this);
        // this.pause.off(cc.Node.EventType.TOUCH_START, this.GameOver, this);

        var _this = this;
        this.scheduleOnce(function () {
            _this.gamePanel.active = false;
            _this.endPanel.active = true;

            _this.RefreshMaxScore();
            _this.refreshEndData();
            _this.LightRotate();
        }, 1);

    }
    //更新结算界面数据
    public refreshEndData() {
        this.scoreNum.getComponent(cc.Label).string = this.score.toString();
        this.beatNum.getComponent(cc.Label).string = "击败了全球" + Util.randNum(60, 100) + "%的玩家";
    }
    // 更新得分和西瓜数目
    public UpdateScoreAndWaterMellonNum() {
        this.scoreLable.string = this.score.toString();
        this.watermellonNumLable.string = this.watermellonNum.toString();
    }
    // 一秒后生成水果，同时判断是否游戏结束
    public CreatFood() {
        var _this = this;
        this.scheduleOnce(function () {
            _this.Creat();
            _this.JudgeGameOver();
        }, 1);
    }
    //判断游戏是否危险（结束）
    public JudgeGameOver() {

        for (var i = 0; i < this.parentPanel.childrenCount; i++) {
            var food = this.parentPanel.children[i].getComponent(Fruit);

            var pos = food.node.position.y + food.radius;
            // console.log(food.isBValid);
            // console.log(pos);
            // console.log(this.dieLine);
            // console.log(this.dangerLine);

            if (food.isBValid && pos > this.dieLine) {
                console.log("游戏结束");
                this.GameOver();
                return;
            }

            if (food.isBValid && pos > this.dangerLine) {
                console.log("危险提示");

                if (this.isCanshowDangerous) {
                    this.Dangerous();
                    break;
                }
            }

        }
    }
    //生成新的水果，不直接调用，使用CreatFood()
    public Creat() {
        cc.log("产生新水果");
        let a = Util.randNum(0, 5);
        cc.log(a);
        let b = cc.instantiate(this.fruitPrefab[a]);
        this.fruitList.push(b.getComponent(Fruit));
        b.setParent(this.parentPanel);
        b.scale = 0;
        b.setPosition(Util.randNum(7, 634), cc.winSize.height - 420 * (cc.winSize.height / 1920));
        this.controledfood = b;
        var rig = this.controledfood.getComponent(cc.RigidBody);
        rig.gravityScale = 0;
        rig.angularDamping = 5;
        cc.tween(b).to(0.1, { scale: 1 }).start();
    }

    //进化新的水果
    public CreatBiggerFruit(postion: cc.Vec2, index: number) {
        cc.log("进化");
        let b = cc.instantiate(this.fruitPrefab[index]);
        this.fruitList.push(b.getComponent(Fruit));
        b.setParent(this.parentPanel);
        b.setPosition(postion.x, postion.y);
        b.scale = 0;
        cc.tween(b).to(1, { scale: 1 }, { easing: 'elasticOut' }).start();
    }
    //点击屏幕
    private MouseJump(event) {
        if (this.controledfood != null) {
            this.controledfood.setPosition(event.getLocationX(), cc.winSize.height - 420 * (cc.winSize.height / 1920), 0)
        }
    }
    //长按屏幕
    private MouseMove(event) {

        if (this.controledfood != null) {
            this.controledfood.setPosition(event.getLocationX(), cc.winSize.height - 420 * (cc.winSize.height / 1920), 0);
        }

    }
    //手指离开屏幕
    private MouseUp() {
        if (this.controledfood != null) {
            this.controledfood.getComponent(cc.RigidBody).gravityScale = 2;
            this.controledfood = null;
            cc.log("鼠标抬起");
            this.CreatFood();
        }
    }
    //重新开始游戏
    public RestartGame() {
        if(this.bannerAd){
            this.bannerAd.show();
        }
        
        for (var i = 0; i < this.parentPanel.childrenCount; i++) {
            this.parentPanel.children[i].destroy();
        }
        this.watermellonNum = 0;
        this.score = 0;
        this.GameStart();
    }

    start() {
        this.GameStart();
        this.dangerLine = cc.winSize.height - (1920 - 1160) * (cc.winSize.height / 1920);
        this.dieLine = cc.winSize.height - (1920 - 1360) * (cc.winSize.height / 1920);

        this.dangerPanel.y = cc.winSize.height - (1920 - 1520) * (cc.winSize.height / 1920);
        if (cc.sys.platform === cc.sys.WECHAT_GAME) {
            this.initWX();
        }
    }

    initWX() {
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        })

        wx.onShareTimeline(() => {
            // 用户点击了“分享到朋友圈”按钮
            return {
                title: '99%的人合成不了的大火锅！你敢试试吗？'
            }
        })

        wx.onShareAppMessage(() => {
            // 用户点击了“转发”按钮
            return {
                title: '99%的人合成不了的大火锅！你敢试试吗？'
            }
        })

        let { screenWidth, screenHeight } = wx.getSystemInfoSync();

        this.bannerAd = wx.createBannerAd({
            adUnitId: 'adunit-148efed69a2ae55d',
            adIntervals: 60,
            style: {
                left: 0,
                top: 0,
                width: 0,
                height: 0
            }
        })

        this.bannerAd.onResize(() => {
            this.bannerAd.style.width = screenWidth * 0.5,
                this.bannerAd.style.left = (screenWidth - this.bannerAd.style.realWidth) * 0.5,
                this.bannerAd.style.top = screenHeight - this.bannerAd.style.realHeight
        })

        this.bannerAd.onError(err => {
            console.log(err)
        })

        this.bannerAd.show()
    }

    //游戏开始逻辑
    GameStart() {
        this.canvas.on(cc.Node.EventType.TOUCH_MOVE, this.MouseMove, this);
        this.canvas.on(cc.Node.EventType.TOUCH_END, this.MouseUp, this);
        this.canvas.on(cc.Node.EventType.TOUCH_CANCEL, this.MouseUp, this);
        this.canvas.on(cc.Node.EventType.TOUCH_START, this.MouseJump, this);
        this.endPanel.active = false;
        this.gamePanel.active = true;
        this.CreatFood();
        var _this = this;
        this.action = cc.sequence(cc.blink(2, 4), cc.callFunc(function () {
            _this.isCanshowDangerous = true;
        }));
        this.isCanshowDangerous = true;
    }

    onLoad() {
        Player.instance = this;
        cc.director.getPhysicsManager().enabled = true;
        cc.director.getCollisionManager().enabled = true;
        cc.director.getPhysicsManager().gravity = cc.v2(0, -960);
        // cc.director.getCollisionManager().enabledDebugDraw = true;
    }
    update() {
        this.UpdateScoreAndWaterMellonNum();
    }
    public ShowRank(): void {
        if (cc.sys.platform === cc.sys.WECHAT_GAME) {
            
        // 定义插屏广告
        let interstitialAd = null

        // 创建插屏广告实例，提前初始化
        if (wx.createInterstitialAd) {
            interstitialAd = wx.createInterstitialAd({
                adUnitId: 'adunit-268d35b602727564'
            })
        }

        // 在适合的场景显示插屏广告
        if (interstitialAd) {
            interstitialAd.show().catch((err) => {
                console.error(err)
            })
        }

            wx.postMessage({
                message: 'Show'
            })
        }

    }
    public RefreshMaxScore(): void {
        if (cc.sys.platform === cc.sys.WECHAT_GAME) {
            wx.postMessage({
                message: 'RefreshMaxScore',
                maxScore: this.score.toString(),
                watermellonNum: this.watermellonNum.toString()
            })
        }


    }

}
